package com.fitz.cluster;

import com.fitz.exception.RpcException;
import com.fitz.proxy.RpcReferenceBean;
import com.fitz.remote.client.ConsumerClient;
import com.fitz.remote.model.RpcRequest;
import com.fitz.remote.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 快速失败，只发起一次调用，失败立即报错
 * @author fitz 2020-5-21 15:24
 */
@Slf4j
public class FailFastStrategy extends AbstractClusterStrategy {

    @Override
    public RpcResponse call(RpcRequest rpcRequest, RpcReferenceBean referenceBean) {
        ConsumerClient client = getClient(referenceBean);
        RpcResponse rpcResponse = new RpcResponse();
        if (client == null){
            rpcResponse.setErrorMessage("remote call error,client is null");
            rpcResponse.setRequestId(rpcRequest.getRequestId());
            return rpcResponse;
        }
        try {
            rpcResponse =  sendRequest(rpcRequest,client);
            if (StringUtils.isNotBlank(rpcResponse.getErrorMessage())){
                throw new RpcException(rpcResponse.getErrorMessage());
            }
            return rpcResponse;
        }finally {
            returnClient(client);
        }
    }
}
